<template>
  <div class="box"
       id="waterTreeList">
    <Row>
      <Col :xs="5"
           :sm="5"
           :md="5"
           :lg="5"
           class="Col_left"
           :style="{'height':Coleheight}">
      <Tree :data="TreeList"
            :multiple="false"
            id="waterBarTree"
            children-key='childs'
            @on-select-change="check"
            @on-check-change="clickCheck"
            :load-data="loadData"
            @on-toggle-expand="toggle"
            ref="treeSelect"></Tree>
      </Col>
      <Col :xs="19"
           :sm="19"
           :md="19"
           :lg="19"
           class="Col_right">
      <div class="Col_right_list">
        <!-- <div style="margin-bottom:24px;text-align: end;padding:30px 30px 0 0"
             v-if="showbtn">
          <Button type="primary"
                  @click="add"
                  style="width:80px">添加</Button>
        </div> -->
        <Row type='flex'
             justify='end'
             style='padding:20px'
             v-if="showbtn">
          <Col><Button type="primary"
                  v-if="categoryId"
                  @click="add"
                  style="width:80px;">添加</Button></Col>
        </Row>
        <Table :columns="columns7"
               :height="this.tableHeight"
               class="table-list"
               :data="dataList"
               v-if="showtable">
          <template slot-scope="{ row,index }"
                    slot="action">
            <i class="iconsys iconedit"
               title="编辑"
               @click="uptShow(row,index)">
            </i>
            <Poptip confirm
                    title="你确定要删除吗？"
                    @on-ok="remove(row.productId,index)"
                    class="poptip_del"
                    @on-cancel="cancel">
              <i class="iconsys icondel"
                 title="删除">
              </i>
            </Poptip>
          </template>
        </Table>
        <!-- <div class="content_page" v-if="showtable">
                  <span>共计100条</span>
                  <Page :total="50"  @on-change="pageNum" class-name="page" show-sizer/>
              </div> -->
      </div>
      <div class="Col_right_detail"
           v-if="showdetail">
        <p>
          <span>商品详情</span>
          <Button type="default"
                  style="width:80px"
                  @click="upt">修改</Button>
        </p>
        <ul>
          <li>
            <span class="Col_right_detail_name">商品名称:</span>
            <span style="flex:1">{{productDetails.productName}}</span>
          </li>
          <li>
            <span class="Col_right_detail_name">简称:</span>
            <span style="flex:1">{{productDetails.spelling}}</span>
          </li>
          <li>
            <span class="Col_right_detail_name">单位:</span>
            <span style="flex:1">{{productDetails.unit}}</span>
          </li>
          <li>
            <span class="Col_right_detail_name">现金购买:</span>
            <span style="flex:1">{{productDetails.productPrice}}元
            </span>
          </li>
          <li>
            <span class="Col_right_detail_name">游戏币购买:</span>
            <span style="flex:1">{{productDetails.productCoinPrice}}元
            </span>
          </li>
          <li>
            <span class="Col_right_detail_name">上传图片:</span>
            <span style="flex:1">
              <img :src="productDetails.productImage"
                   style="width:96px;height:96px;vertical-align:top;">
            </span>
          </li>
        </ul>
      </div>
      </Col>
    </Row>
    <Drawer :title="title"
            :closable="false"
            v-model="value1"
            id="waterbar_drawer"
            width="540"
            @on-close="closed">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            v-if="true">
        <FormItem label="商品名称："
                  prop="productName">
          <Input v-model="formValidate.productName"
                 @on-keyup="changeName"
                 :maxlength="14"
                 placeholder="最多输入14字"
                 class="box_input"></Input>
        </FormItem>
        <FormItem label="简拼："
                  prop="spelling">
          <Input v-model="formValidate.spelling"
                 @on-keyup="filterSpace"
                 :maxlength="10"
                 placeholder="最多输入10字"
                 class="box_input"></Input>
        </FormItem>
        <FormItem label="单位："
                  prop="unit">
          <Select v-model="formValidate.unit"
                  class="box_input">
            <Option value='个'>个</Option>
            <Option value='袋'>袋</Option>
            <Option value='瓶'>瓶</Option>
            <Option value='杯'>杯</Option>
            <Option value='盘'>盘</Option>
            <Option value='份'>份</Option>
          </Select>
        </FormItem>
        <FormItem label="现金购买："
                  prop="productPrice">
          <Input v-model="formValidate.productPrice"
                 :maxlength="7"
                 @on-blur="priceBlur"
                 @on-keyup="changeprice"
                 placeholder="输入范围为0.00~9999.99"
                 class="box_input"></Input>
          <span style="margin-left:10px">元</span>
        </FormItem>
        <FormItem label="游戏币购买："
                  prop="productCoinPrice">
          <Input v-model="formValidate.productCoinPrice"
                 @on-keyup="changecoinNum"
                 @on-blur="priceproductCoinPrice"
                 :maxlength="6"
                 placeholder="输入范围为1~999999"
                 class="box_input"></Input>
          <span style="margin-left:10px">枚</span>
        </FormItem>
        <FormItem label="上传图片:"
                  prop="productImage"
                  class="set_ct_form_up">
          <Upload ref="upload"
                  :format="['jpg','png']"
                  :max-size="100"
                  :on-success="handleSuccess"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  type="drag"
                  :show-upload-list="false"
                  :action="$config.uploadImg"
                  style="display: inline-block;width:96px;">
            <img :src="formValidate.productImage?formValidate.productImage:defaultUrl"
                 style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                 alt="">
            <p v-if="formValidate.productImage"
               class="replace_tit">更换</p>
          </Upload>
          <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;">支持格式：.jpg、.png；规格：235*110；大小：≤100K</div>
        </FormItem>
      </Form>
      <div class="demo-drawer-footer">
        <Button @click="handleReset"
                style="margin-right:20px;width:72px">取消</Button>
        <Button type="primary"
                @click="handleSubmit"
                :disabled='isDisabled'
                style="width:72px">保存</Button>
      </div>
    </Drawer>
  </div>
</template>
<script>
import { setproductDelete, setproductSave, getProductCategory, lookShopInfo } from '@/api/setting'
export default {
  data () {
    return {
      tableHeight: 0,
      Arrindex: 0,
      value1: false,
      showbtn: true,
      isudp: false,
      title: '添加水吧商品',
      showdetail: false,
      showtable: true,
      isDisabled: false,
      isDelete: true,
      TreeList: [], // 树形列表
      giftParmas: {
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId,
        categoryType: 0,
        parentId: 0
      },
      list: ['游戏卡', '饮料', '票', '小商品', '次卡产品', '电子币', '闸机消费'],
      businessid: '',
      defaultUrl: require('@/assets/images/default.png'),
      productDetails: {

      },
      Coleheight: '',
      categoryId: '',
      formValidate: {
        categoryId: '',
        productId: null,
        productType: 11, // 水吧商品设置
        priceType: 4,
        productName: '', // 商品名称
        spelling: '', // 简拼
        unit: '', // 单位
        productPrice: '', // 现金购买
        productCoinPrice: '', // 游戏币购买
        productImage: '',
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      },
      ruleValidate: {
        productName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        productPrice: [
          { required: true, message: '现金购买不能为空', trigger: 'blur' },
          { required: true, message: '输入范围为0.00到9999.99之间', trigger: 'blur', pattern: /^\d{1,4}(\.\d{1,2})?$/ }
        ],
        productCoinPrice: [{
          required: true, message: '游戏币购买不能为空', trigger: 'blur'
        }, { required: true, message: '输入范围为1到999999之间', type: 'string', trigger: 'blur', pattern: /^[1-9][0-9]{0,5}$/ }],
        productImage: [{ required: true, message: '上传图片不能为空' }]
      },
      columns7: [
        {
          title: '商品名称',
          key: 'productName'
        },
        {
          title: '简拼',
          key: 'spelling'
        },
        {
          title: '单位',
          key: 'unit',
          align: 'center'
        },
        {
          title: '游戏币购买',
          key: 'productCoinPrice',
          align: 'center'
        },
        {
          title: '现金购买',
          key: 'productPrice',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          slot: 'action'
        }
      ],
      dataList: [
      ]
    }
  },
  computed: {
  },
  created () {
  },
  mounted () {
    // this.getleftTree()
    this.Coleheight = document.documentElement.clientHeight - 190 + 'px'
    this.getGiftList()
    if (!this.hasPermission('moms:setting:restzonegoods')) {
      this.$router.replace({ name: 'error_401' })
    }
  },
  methods: {
    changeName () {
      this.formValidate.productName = this.formValidate.productName.replace(/\s+/g, '')
    },
    filterSpace () {
      this.formValidate.spelling = this.formValidate.spelling ? this.formValidate.spelling.replace(/\s+/g, '') : ''
    },
    changeprice () {
      this.changeNum()
    },
    changeNum () {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (this.formValidate.productPrice !== '' && this.formValidate.productPrice.substring(0, 1) === '.') {
        this.formValidate.productPrice = ''
      }
      this.formValidate.productPrice = this.formValidate.productPrice.replace(/^0*(0\.|[1-9])/, '$1')// 粘贴不生效
      this.formValidate.productPrice = this.formValidate.productPrice.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      this.formValidate.productPrice = this.formValidate.productPrice.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      this.formValidate.productPrice = this.formValidate.productPrice.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formValidate.productPrice = this.formValidate.productPrice.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      // this.formValidate.productPrice = this.formValidate.productPrice.replace(/\.{2,}/g, '.')
      if (this.formValidate.productPrice.indexOf('.') < 0 && this.formValidate.productPrice !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (this.formValidate.productPrice.substring(0, 1) === '0' && this.formValidate.productPrice.length === 2) {
          this.formValidate.productPrice = this.formValidate.productPrice.substring(1, this.formValidate.productPrice.length)
        }
      }
      if (this.formValidate.productPrice > 9999.99) {
        this.formValidate.productPrice = this.formValidate.productPrice.substring(0, 4)
      }
    },
    priceproductCoinPrice () {
      this.formValidate.productName = this.formValidate.productName.replace(/\s+/g, '')
    },
    priceBlur () {
      this.formValidate.productPrice = this.formValidate.productPrice + ''
      this.formValidate.productPrice = this.formValidate.productPrice.replace(/[^\d.]/g, '')
      if (this.formValidate.productPrice === '') {
        this.formValidate.productPrice = ''
      } else if (this.formValidate.productPrice.indexOf('.') === -1) {
        this.formValidate.productPrice = this.formValidate.productPrice + '.00'
      } else if (this.formValidate.productPrice.indexOf('.')) {
        let ste = this.formValidate.productPrice.substring(this.formValidate.productPrice.indexOf('.') + 1)
        if (!ste) {
          this.formValidate.productPrice = this.formValidate.productPrice + '00'
        }
        if (ste.length === 1) {
          this.formValidate.productPrice = this.formValidate.productPrice + '0'
        } if (ste.length > 2) {
          this.formValidate.productPrice = this.formValidate.productPrice.substring(0, this.formValidate.productPrice.indexOf('.') + 3)
        }
      }
    },
    changecoinNum () {
      this.formValidate.productCoinPrice = this.formValidate.productCoinPrice.replace(/^(0+)|[^\d]+/g, '')
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '上传的图片大小不能超过100k'
      })
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传的图片格式错误'
      })
    },
    // 获取图片尺寸
    getcicun (url) {
      var img = new Image()
      img.src = url
      var _this = this
      img.onload = function () {
        if (img.width !== 235 && img.height !== 110) {
          _this.formValidate.productImage = ''
          _this.$Notice.warning({
            title: '上传的图片规格不符'
          })
        }
      }
    },
    // 获取水吧商品类型
    getGiftList () {
      getProductCategory(this.giftParmas).then(res => {
        if (res.data.status === 200) {
          this.TreeList = res.data.data
          this.TreeList.forEach(ele => {
            this.$set(ele, 'title', ele.categoryName)
            this.$set(ele, 'loading', false)
          })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 延迟加载
    loadData (item, callback) {
      this.categoryId = item.categoryId
      setTimeout(() => {
        lookShopInfo({
          categoryId: item.categoryId,
          businessItem: '',
          shopId: this.$route.query.id
        }).then(res => {
          if (res.data.status === 200) {
            let arr = res.data.data
            if (res.data.data.length) {
              arr.forEach(ele => {
                this.$set(ele, 'title', ele.productName)
                // this.$set(ele, 'loading', false)
              })
            }
            this.dataList = arr
            callback(arr)
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      }, 1000)
    },
    // 上传图片
    handleSuccess (response, file, fileList) {
      this.formValidate.productImage = response.full_img_url
      this.getcicun(this.formValidate.productImage)
    },
    // 新增
    add () {
      this.title = '添加水吧商品'
      this.value1 = true
      this.isudp = false
    },
    // 修改
    upt () {
      this.title = '修改水吧商品'
      this.isudp = true
      this.formValidate = {
        categoryId: this.productDetails.categoryId,
        productId: this.productDetails.productId,
        productType: 11, // 水吧商品设置
        priceType: 4,
        productName: this.productDetails.productName, // 商品名称
        spelling: this.productDetails.spelling, // 简拼
        unit: this.productDetails.unit, // 单位
        productPrice: this.productDetails.productPrice + '', // 现金购买
        productCoinPrice: this.productDetails.productCoinPrice + '', // 游戏币购买
        productImage: this.productDetails.productImage,
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      }
      this.value1 = true
    },
    // 更新列表
    upDateList (idx) {
      lookShopInfo({
        categoryId: idx,
        businessItem: '',
        shopId: this.$route.query.id
      }).then(res => {
        if (res.data.status === 200) {
          let arr = res.data.data
          if (res.data.data.length) {
            arr.forEach(ele => {
              this.$set(ele, 'title', ele.productName)
              // this.$set(ele, 'loading', false)
            })
          }
          this.dataList = arr
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 关闭抽屉
    closed () {
      this.$refs.formValidate.resetFields()
      this.value1 = false
    },
    // 提交效验
    handleSubmit () {
      if (this.title === '添加水吧商品') {
        this.formValidate.categoryId = this.categoryId
        this.formValidate.productId = null
        this.$refs.formValidate.validate((valid) => {
          if (valid) { // 验证保存
            if (this.isDisabled) {
              return
            }
            this.isDisabled = true
            setproductSave(this.formValidate).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                let obj = res.data.data
                this.TreeList.forEach(ele => {
                  if (ele.categoryId === obj.categoryId) {
                    ele.childs.unshift({ ...obj, title: obj.productName })
                  }
                })
                this.$Message.success('新增成功')
                this.upDateList(this.categoryId)
                this.getGiftList()
                //  this.loadData({categoryId:this.categoryId})
                this.$refs.formValidate.resetFields()
                this.value1 = false
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }
        })
      } else {
        this.$refs.formValidate.validate((valid) => {
          if (valid) { // 验证保存
            if (this.isDisabled) {
              return
            }
            this.isDisabled = true
            setproductSave(this.formValidate).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                this.$Message.success('修改成功')
                let upobj = res.data.data
                if (!this.isudp) {
                  this.TreeList.forEach((ele, index, atr) => {
                    if (ele.categoryId === upobj.categoryId) {
                      ele.childs.forEach((elt, i, arr) => {
                        if (elt.productId === upobj.productId) {
                          this.$set(this.TreeList[index].childs, i, { ...arr[i], ...upobj, title: upobj.productName })
                        }
                      })
                      atr[index] = ele
                    }
                  })
                } else {
                  this.productDetails = { ...upobj, title: upobj.productName }
                  this.TreeList.forEach((ele, index, atr) => {
                    if (ele.categoryId === this.productDetails.categoryId) {
                      ele.childs.forEach((elt, i, arr) => {
                        if (elt.productId === this.productDetails.productId) {
                          // arr[i] = { ...arr[i], ...this.productDetails }
                          this.$set(this.TreeList[index].childs, i, { ...arr[i], ...this.productDetails })
                        }
                      })
                    }
                  })
                }
                this.upDateList(this.categoryId)
                this.$refs.formValidate.resetFields()
                this.value1 = false
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }
        })
      }
    },
    // 重置
    handleReset () {
      this.$refs.formValidate.resetFields()
      this.value1 = false
    },
    // 编辑
    uptShow (row, index) { // 编辑
      this.title = '修改水吧商品'
      this.isudp = false
      this.formValidate = {
        categoryId: row.categoryId,
        productId: row.productId,
        productType: 11, // 水吧商品设置
        priceType: 4,
        productName: row.productName, // 商品名称
        spelling: row.spelling, // 简拼
        unit: row.unit, // 单位
        productPrice: row.productPrice + '', // 现金购买
        productCoinPrice: row.productCoinPrice + '', // 游戏币购买
        productImage: row.productImage,
        shopId: this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      }
      this.value1 = true
    },
    // 移除
    remove (idx, index) { // 删除
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        setTimeout(() => {
          setproductDelete({
            'productId': idx
          }).then((res) => {
            this.isDelete = true
            if (res.data.status === 200) {
              this.Arrindex = idx
              this.upDateList(this.categoryId)
              this.TreeList.forEach(ele => {
                if (ele.categoryId === this.categoryId) {
                  ele.childs.forEach((elt, idex, arr) => {
                    if (elt.productId === idx) {
                      arr.splice(idex, 1)
                    }
                  })
                }
              })
              this.$Message.success('删除成功')
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    // 取消
    cancel () { // 取消删除的回调
      this.$refs.formValidate.resetFields()
      this.value1 = false
    },
    // 展开和收起
    toggle (a, b) {
    },
    check (a, b) { // 点击子商品切换详情
      this.productDetails = b
      this.categoryId = b.categoryId
      this.tableHeight = 0
      lookShopInfo({
        categoryId: this.categoryId,
        businessItem: '',
        shopId: this.$route.query.id
      }).then(res => {
        if (res.data.status === 200) {
          let arr = res.data.data
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
          if (res.data.data.length) {
            arr.forEach(ele => {
              this.$set(ele, 'title', ele.productName)
            })
          }
          this.dataList = arr
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
      // if(!b.hasOwnProperty('title'))
      // {
      //    b.title = this.productDetails.productName
      // }
      if (!b.hasOwnProperty('childs')) {
        this.showdetail = true
        this.showtable = false
        this.showbtn = false
      } else {
        this.showdetail = false
        this.showtable = true
        this.showbtn = true
        this.dataList = b.childs
      }
    },
    clickCheck (a, b) { // 点击勾选
    }
  }
}
</script>
<style lang="less">
#waterbar_drawer {
  .ivu-upload {
    width: 96px;
    height: 96px;
    position: relative;
    .replace_tit {
      position: absolute;
      bottom: 0;
      width: 96px;
      opacity: 0.6;
      background: #2d8cf0;
      height: 24px;
      text-align: center;
      line-height: 24px;
      font-size: 12px;
      color: #ffffff;
      display: none;
    }
  }
  .ivu-upload:hover .replace_tit {
    display: block;
  }
}
</style>
<style lang="less" scoped>
.box {
  .Col_left {
    // height: 780px;
    box-sizing: border-box;
    border-right: 1px solid #e8eaec;
    padding: 20px 0 0 15px;
    overflow: auto;
  }
  .Col_right {
    .content_page {
      height: 80px;
      line-height: 80px;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      .page {
        margin-left: 2%;
      }
    }
    .Col_right_detail {
      width: 598px;
      padding: 30px 0 0 53px;
      p {
        margin-bottom: 70px;
        span {
          color: #17233d;
          font-size: 14px;
          margin-right: 32px;
          font-weight: bold;
        }
      }
      ul {
        color: #464c5b;
        padding-left: 30px;
        li {
          margin-bottom: 15px;
          display: flex;
          .Col_right_detail_name {
            width: 82px;
            text-align: right;
            display: inline-block;
            margin-right: 10px;
          }
        }
      }
    }
  }
}
</style>
<style>
ul,
li {
  padding: 0;
  margin: 0;
  list-style: none;
}
.box_input {
  width: 280px;
}
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
#waterTreeList .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
  left: 14px;
}
.set_ct_form_up .ivu-form-item-content {
  display: flex;
}
</style>
